package part20IO流.hw;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import part20IO流.Person;

public class 对象流练习 {

	public static void main(String[] args) {
		对象流练习 t = new 对象流练习();
		// t.序列化();
		t.反序列化();
	}

	public void 序列化() {
		File file = new File("persons.txt");
		// 文件输出流
		FileOutputStream fos = null;
		// 对象输出流
		ObjectOutputStream oos = null;
		try {
			fos = new FileOutputStream(file);
			oos = new ObjectOutputStream(fos);

			List<Person> persons = new ArrayList<Person>();
			persons.add(new Person("xx", "19"));
			persons.add(new Person("xx2", "29"));
			persons.add(new Person("xx3", "39"));
			persons.add(new Person("xx4", "49"));
			// 将对象写入流中
			oos.writeObject(persons); // 要做序列化的对象的类必须实现序列化接口

			System.out.println("----写入完毕 对象序列化成功---");

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (oos != null) {
					oos.close();
				}
				if (fos != null) {
					fos.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void 反序列化() {
		// 文件输入流
		FileInputStream fis = null;
		// 对象输入流
		ObjectInputStream ois = null;
		try {

			fis = new FileInputStream("persons.txt");
			ois = new ObjectInputStream(fis);

			// 从流中读取对象信息
			List<Person> list = (List<Person>) ois.readObject();
			System.out.println(list);

			System.out.println("----读取完毕 对象反序列化成功---");
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			try {
				if (ois != null) {
					ois.close();
				}
				if (fis != null) {
					fis.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
